package bar.dark.lee;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.TextView;
import bar.dark.lee.cashdrawing.CashTabActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.CalendarPickerDialog;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.fan.FanTabActivity;
import bar.dark.lee.insert.InsertTabActivity;
import bar.dark.lee.manager.ManagerTabActivity;
import bar.dark.lee.manager.card.CreditCardResultDateData;
import bar.dark.lee.select.SelectDialogActivity;
import bar.dark.lee.setting.SettingActivity;
import bar.dark.lee.setting.TipsActivity;
import bar.dark.lee.stats.StatsDialogActivity;
import bar.dark.lee.widget.WidgetGetSqlQuery;

public class MainActivity extends SuperActivity implements OnClickListener {
    public static final String SELECT_FLAG = "select_flag";

	public static final String START_DATE = "start_date";
	public static final String END_DATE = "end_date";

	public static final String MAIN_KEY = "main_key";
	public static final String MAIN_NUMBER = "main_number";

	public static final String MAIN_TO_YEAR = "main_to_year";
	public static final String MAIN_TO_MONTH = "main_to_month";
	public static final String MAIN_TO_DAY = "main_to_day";

	private DBSQLite dbSql;
	
	private View mBtnInsert; // 입력버튼
	private View mBtnSelect; // 조회버튼
	private View mBtnStats; // 통계버튼
	private View mBtnSetting; // 셋팅버튼
	private View mBtnCashDrawing;	// 현금인출
	private View mBtnMyManager; // 자산관리
	private View mBtnMyFan; // 부채관리
	private View mBtnMyTips; // 도움말관리
	
	private TextView leftTitle1; // 윈쪽위 첫번째 타이틀
	private TextView leftTitle2; // 윈쪽위 두번째 타이틀
	private TextView leftTitle3; // 윈쪽위 세번째 타이틀
	private TextView leftTitle4; // 윈쪽위 네번째 타이틀
	private TextView totalMoney; // 총금액
	private TextView bankMoney; // 통장금액
	private TextView realMoney; // 현금
	private TextView creditMoney; // 결제금액
	
	private TextView middleTitle1; // 중간 첫번째 타이틀
	private TextView middleTitle2; // 중간 두번째 타이틀
	private TextView middleTitle3; // 중간 세번째 타이틀
	private TextView middleTitle4; // 중간 네번째 타이틀
	private TextView middleTitle5; // 중간 다섯번째 타이틀
	private TextView middleTitle6; // 중간 여섯번째 타이틀
	
	private TextView monthOutMoney; // 이달의 지출
	private TextView monthInMoney; // 이달의 수입
	private TextView monthPostMoney; // 이달의 카드대금
	private TextView todayOutMoney; // 오늘의 지출
	private TextView todayInMoney; // 오늘의 수입
	private TextView todayPostMoney; // 오늘의 카드대금
	
	private TextView date;
	private TextView weekDay;
	private TextView weekDay2;
	private ImageButton leftDayButton;
	private ImageButton rightDayButton;
	private TextView startTextView; // 시작일 텍스트 뷰 
	
	private View dateLayout;
	private View toDayLayout;
	private View toMonthLayout;
	
	private ImageButton leftMonthButton;
	private ImageButton rightMonthButton;
	
	private HorizontalScrollView monthScrollView;
	private HorizontalScrollView todayScrollView;
	
	private int toYear;
	private int toMonth;
	private int toDay;
	
	private Intent intent;
	
	private boolean btnEnable = true;
	
	private BigDecimal dbTotalMoney = BigDecimal.ZERO;
	
	private ArrayList<CreditCardResultDateData> creditResultList = null;
	
	private boolean bankFlag;
	
	private WidgetGetSqlQuery viewQuery;
	
	private int dbCount = 0;
	
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        
        setGoneTitle();
        
        // 디비를 가져온다.
        dbSql = DBSQLite.getInstance(this);
        
        // 위젯 통합 디비 클래스를 가져온다.
        viewQuery = new WidgetGetSqlQuery(superContext);
        
		mBtnInsert = findViewById(R.id.MAIN_btnInsert);
		mBtnSelect = findViewById(R.id.MAIN_btnSelect);
		mBtnStats = findViewById(R.id.MAIN_btnStats);
		mBtnSetting = findViewById(R.id.MAIN_btnSetting);
		mBtnCashDrawing = findViewById(R.id.MAIN_btnCashDrawing);
		mBtnMyManager = findViewById(R.id.MAIN_btnMyManager);
		mBtnMyFan = findViewById(R.id.MAIN_btnMyFan);
		mBtnMyTips = findViewById(R.id.MAIN_btnMyTips);
		
		leftTitle1 = (TextView) findViewById(R.id.mainLeftTitle1);
		leftTitle2 = (TextView) findViewById(R.id.mainLeftTitle2);
		leftTitle3 = (TextView) findViewById(R.id.mainLeftTitle3);
		leftTitle4 = (TextView) findViewById(R.id.mainLeftTitle4);
		middleTitle1 = (TextView) findViewById(R.id.mainMonthInTitle);
		middleTitle2 = (TextView) findViewById(R.id.mainMonthOutTitle);
		middleTitle3 = (TextView) findViewById(R.id.mainMonthPostTitle);
		middleTitle4 = (TextView) findViewById(R.id.mainTodayInTitle);
		middleTitle5 = (TextView) findViewById(R.id.mainTodayOutTitle);
		middleTitle6 = (TextView) findViewById(R.id.mainTodayPostTitle);
		totalMoney = (TextView) findViewById(R.id.mainTotalMoney);
		bankMoney = (TextView) findViewById(R.id.mainBankMoney);
		realMoney = (TextView) findViewById(R.id.mainRealMoney);
		creditMoney = (TextView) findViewById(R.id.mainCreditMoney);
		todayOutMoney = (TextView) findViewById(R.id.mainTodayOutMoney);
		todayInMoney = (TextView) findViewById(R.id.mainTodayInMoney);
		todayPostMoney = (TextView) findViewById(R.id.mainTodayPostMoney);
		date = (TextView) findViewById(R.id.mainDate);
		weekDay = (TextView) findViewById(R.id.mainDay);
		weekDay2 = (TextView) findViewById(R.id.mainDay2);
		leftDayButton = (ImageButton) findViewById(R.id.mainLeftDateButton);
		rightDayButton = (ImageButton) findViewById(R.id.mainRightDateButton);
		monthOutMoney = (TextView) findViewById(R.id.mainMonthOutMoney);
		monthInMoney = (TextView) findViewById(R.id.mainMonthInMoney);
		monthPostMoney = (TextView) findViewById(R.id.mainMonthPostMoney);
		leftMonthButton = (ImageButton) findViewById(R.id.mainLeftMonthButton);
		rightMonthButton = (ImageButton) findViewById(R.id.mainRightMonthButton);
		startTextView = (TextView) findViewById(R.id.mainStartDate);
		
		monthScrollView = (HorizontalScrollView) findViewById(R.id.mainMonthScorllView);
		todayScrollView = (HorizontalScrollView) findViewById(R.id.mainTodayScrollView);
		
		dateLayout = findViewById(R.id.mainDateLayout);
		toDayLayout = findViewById(R.id.main_toDayLayout);
		toMonthLayout = findViewById(R.id.main_toMonthLayout);
		
		mBtnInsert.setOnClickListener(this);
		mBtnSelect.setOnClickListener(this);
		mBtnStats.setOnClickListener(this);
		mBtnSetting.setOnClickListener(this);
		mBtnCashDrawing.setOnClickListener(this);
		mBtnMyManager.setOnClickListener(this);
		mBtnMyFan.setOnClickListener(this);
		mBtnMyTips.setOnClickListener(this);
		leftDayButton.setOnClickListener(this);
		rightDayButton.setOnClickListener(this);
		leftMonthButton.setOnClickListener(this);
		rightMonthButton.setOnClickListener(this);
		
		setDate();
		
		setScroll();
		
		showNoticeDialog();
    }
    
    /**
     * 스크롤 위치를 예전꺼로 이동 시킨다 .
     */
    private void setScroll()
	{
    	SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
    	
    	final int todayX = pref.getInt(BDConstents.TODAY_SCROLL_X, 0);
    	final int todayY = pref.getInt(BDConstents.TODAY_SCROLL_Y, 0);
    	
    	final int monthX = pref.getInt(BDConstents.MONTH_SCROLL_X, 0);
    	final int monthY = pref.getInt(BDConstents.MONTH_SCROLL_Y, 0);
    	
    	todayScrollView.postDelayed(new Runnable()
		{
			@Override
			public void run()
			{
				todayScrollView.scrollBy(todayX, todayY);
			}
		}, 100);
    	
    	monthScrollView.postDelayed(new Runnable()
		{
			@Override
			public void run()
			{
				monthScrollView.scrollBy(monthX, monthY);
			}
		}, 100);
	}

	private void showNoticeDialog()
	{
    	SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
    	
    	int noticeFlag = pref.getInt(BDConstents.NOTICE_FLAG, 0);
    	
    	if (noticeFlag < BDConstents.NOTICE_REVISION)
    	{
    		AlertDialog.Builder dialog = new AlertDialog.Builder(superContext);
			dialog.setTitle("공지사항");
			dialog.setMessage(getString(R.string.notice));
			
			dialog.setPositiveButton("다시보지않기", new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					dialog.dismiss();
					setNoticeCheck();
					showFirstDialog();
				}
			});
			
			dialog.setNegativeButton("확인", new DialogInterface.OnClickListener() 
			{
				@Override
				public void onClick(DialogInterface dialog, int which) 
				{
					dialog.dismiss();
					showFirstDialog();
				}
			});
			
			dialog.setCancelable(false);
			dialog.show();
    	}
	}

	private void showFirstDialog() 
	{
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
    	
    	int flag = pref.getInt(BDConstents.FIRST_START, 0);
		
		if (flag == 0)
		{
			AlertDialog.Builder dialog = new AlertDialog.Builder(superContext);
			dialog.setTitle("알림");
			dialog.setMessage("가계부를 처음 시작하셨습니다. " +
					"먼저 현금, 통장, 카드를 등록해 주셔야 편리한 사용이 가능합니다. " +
					"등록을 위해 자산관리 화면으로 이동 하시겠습니까? " +
					"잘 모르실경우 우측 상단의 도움말을 이용해주세요.");
			
			dialog.setPositiveButton("자산관리로", new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					Intent intent = new Intent(MainActivity.this, ManagerTabActivity.class);
					startActivity(intent);
					setFirstCheck();
				}
			});
			
			dialog.setNegativeButton("바로시작", new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					dialog.dismiss();
					setFirstCheck();
				}
			});

			dialog.setCancelable(false);
			dialog.show();
		}
	}
    
    private void setFirstCheck()
	{
    	SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
    	SharedPreferences.Editor editor = pref.edit();
    	
    	editor.putInt(BDConstents.FIRST_START, 1);
    	editor.commit();
	}
    
    private void setNoticeCheck()
   	{
       	SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
       	SharedPreferences.Editor editor = pref.edit();
       	
       	editor.putInt(BDConstents.NOTICE_FLAG, BDConstents.NOTICE_REVISION);
       	editor.commit();
   	}

	@Override
    protected void onResume()
    {
    	super.onResume();
    	setDataSetting();
    	btnEnable = true;
    	
//    	adview = new BDAdView(this, ((LinearLayout)findViewById(R.id.adview)));
//		//adview.startAdam();
//		//adview.startTad();
//		adview.startBDAd();
    }
	
	@Override
	protected void onPause()
	{
		super.onPause();
		
//		if (adview != null)
//		{
//			adview.BDAdViewDestroy();
//		}
	}
    
    private void setDate()
	{
    	Calendar cal = Calendar.getInstance();
    	
    	toYear = cal.get(Calendar.YEAR);
    	toMonth = cal.get(Calendar.MONTH);
    	toDay = cal.get(Calendar.DAY_OF_MONTH);
    	int week = cal.get(Calendar.DAY_OF_WEEK);
    	
//    	date.setText(BDUtil.getDate(toYear, toMonth+1, toDay));
//    	weekDay.setText(BDUtil.getWeekDay(week));
    	
    	date.setText(toYear+"년 "+(toMonth+1)+"월");
    	weekDay.setText(toDay+"");
    	BDUtil.WeekDayClass wdClass = new BDUtil.WeekDayClass();
    	wdClass = BDUtil.getWeekDayChinese(toYear, toMonth, toDay);
    	weekDay2.setText(wdClass.getWeekDayStr());
    	weekDay2.setTextColor(wdClass.getWeekDayColor());
    	weekDay.setTextColor(wdClass.getWeekDayColor());
    	
    	dateLayout.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				
				CalendarPickerDialog cpd = new CalendarPickerDialog(superContext, new CalendarPickerDialog.ICalendarPickerDateSetListener() {
					@Override
					public void onDateSet(int year, int monthOfYear, int dayOfMonth) {
						
						date.setText(year+"년 "+(monthOfYear+1)+"월");
				    	weekDay.setText(dayOfMonth+"");
				    	BDUtil.WeekDayClass wdClass = new BDUtil.WeekDayClass();
				    	wdClass = BDUtil.getWeekDayChinese(year, monthOfYear, dayOfMonth);
				    	weekDay2.setText(wdClass.getWeekDayStr());
				    	weekDay2.setTextColor(wdClass.getWeekDayColor());
				    	weekDay.setTextColor(wdClass.getWeekDayColor());
				    	
						toYear = year;
						toMonth = monthOfYear;
						toDay = dayOfMonth;
						
						setDataSetting();
					}
				}, toYear, toMonth, toDay);
				
				cpd.show();
				
//				DatePickerDialog dpd = new DatePickerDialog(MainActivity.this, new OnDateSetListener()
//				{
//					@Override
//					public void onDateSet(DatePicker view, int year, int monthOfYear,
//							int dayOfMonth)
//					{
//						date.setText(year+"년 "+(monthOfYear+1)+"월");
//				    	weekDay.setText(dayOfMonth+"");
//				    	BDUtil.WeekDayClass wdClass = new BDUtil.WeekDayClass();
//				    	wdClass = BDUtil.getWeekDayChinese(year, monthOfYear, dayOfMonth);
//				    	weekDay2.setText(wdClass.getWeekDayStr());
//				    	weekDay2.setTextColor(wdClass.getWeekDayColor());
//				    	weekDay.setTextColor(wdClass.getWeekDayColor());
//				    	
//						toYear = year;
//						toMonth = monthOfYear;
//						toDay = dayOfMonth;
//						
//						setDataSetting();
//					}
//				}, toYear, toMonth, toDay);
//				
//				// 가운데
//				dpd.setButton3("오늘 날짜로", new DialogInterface.OnClickListener() {
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						Calendar calendar = Calendar.getInstance();
//						int year = calendar.get(Calendar.YEAR);
//						int monthOfYear = calendar.get(Calendar.MONTH);
//						int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
//						
//						date.setText(year+"년 "+(monthOfYear+1)+"월");
//				    	weekDay.setText(dayOfMonth+"");
//				    	BDUtil.WeekDayClass wdClass = new BDUtil.WeekDayClass();
//				    	wdClass = BDUtil.getWeekDayChinese(year, monthOfYear, dayOfMonth);
//				    	weekDay2.setText(wdClass.getWeekDayStr());
//				    	weekDay2.setTextColor(wdClass.getWeekDayColor());
//				    	weekDay.setTextColor(wdClass.getWeekDayColor());
//				    	
//						toYear = year;
//						toMonth = monthOfYear;
//						toDay = dayOfMonth;
//						
//						setDataSetting();
//					}
//				});
//				
//				dpd.show();
			}
		});
	}
    
    /**
     * 
     */
	private void setDataSetting()
	{
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		
		/** 시작일로 카드대금 가져올지 기간으로 가져올지 플래그 */
		int postCheck = pref.getInt(BDConstents.MONTH_POSTMONEY_SETTING, 0);
		
		int fanOkNoFlag = pref.getInt(BDConstents.FAN_SETTING_OK_NO, 0);
		
		// 시작일 셋팅
		int startDate = Integer.parseInt(pref.getString(BDConstents.START_DATE, "1"));
    	startTextView.setText(startDate + "");
		
		dbTotalMoney = BigDecimal.ZERO;
		
		String settingKey = pref.getString(BDConstents.BIG_MAIN_SETTING, "0,1,2,3,6,4,5,9,7,8");
		
		String [] key = settingKey.split(",");
		
		if (key.length < 10 )
		{
			settingKey = "0,1,2,3,6,4,5,9,7,8";
			key = settingKey.split(",");
		}
		
		String mainViewMoney = "";
		
		leftTitle1.setText(viewQuery.getName(key[0], 0, 1));
		totalMoney.setTextColor(viewQuery.getColor(key[0]));
		
		if (!key[0].equals(WidgetGetSqlQuery.SECRET))
		{
			mainViewMoney = viewQuery.getMoney(key[0], 0, 1);
			totalMoney.setGravity(Gravity.RIGHT|Gravity.CENTER_VERTICAL);
			totalMoney.setText(BDUtil.getWon(mainViewMoney.toString()) + shape);
			viewQuery.setOnClick(leftTitle1, key[0], 0);
			viewQuery.setOnClick(totalMoney, key[0], 0);
		}
		else
		{
			totalMoney.setGravity(Gravity.CENTER);
			totalMoney.setText("비밀");
			viewQuery.setOnClick(leftTitle1, key[0], 0);
			viewQuery.setOnClick(totalMoney, key[0], 0);
		}
		
		leftTitle2.setText(viewQuery.getName(key[1], 1, 1));
		bankMoney.setTextColor(viewQuery.getColor(key[1]));
		
		if (!key[1].equals(WidgetGetSqlQuery.SECRET))
		{
			mainViewMoney = viewQuery.getMoney(key[1], 1, 1);
			bankMoney.setGravity(Gravity.RIGHT|Gravity.CENTER_VERTICAL);
			bankMoney.setText(BDUtil.getWon(mainViewMoney.toString()) + shape);
			viewQuery.setOnClick(leftTitle2, key[1], 1);
			viewQuery.setOnClick(bankMoney, key[1], 1);
		}
		else
		{
			bankMoney.setGravity(Gravity.CENTER);
			bankMoney.setText("비밀");
			viewQuery.setOnClick(leftTitle2, key[1], 1);
			viewQuery.setOnClick(bankMoney, key[1], 1);
		}
		
		leftTitle3.setText(viewQuery.getName(key[2], 2, 1));
		realMoney.setTextColor(viewQuery.getColor(key[2]));
		
		if (!key[2].equals(WidgetGetSqlQuery.SECRET))
		{
			mainViewMoney = viewQuery.getMoney(key[2], 2, 1);
			realMoney.setGravity(Gravity.RIGHT|Gravity.CENTER_VERTICAL);
			realMoney.setText(BDUtil.getWon(mainViewMoney.toString()) + shape);
			viewQuery.setOnClick(leftTitle3, key[2], 2);
			viewQuery.setOnClick(realMoney, key[2], 2);
		}
		else
		{
			realMoney.setGravity(Gravity.CENTER);
			realMoney.setText("비밀");
			viewQuery.setOnClick(leftTitle3, key[2], 2);
			viewQuery.setOnClick(realMoney, key[2], 2);
		}
		
		leftTitle4.setText(viewQuery.getName(key[3], 3, 1));
		creditMoney.setTextColor(viewQuery.getColor(key[3]));
		
		if (!key[3].equals(WidgetGetSqlQuery.SECRET))
		{
			mainViewMoney = viewQuery.getMoney(key[3], 3, 1);
			creditMoney.setGravity(Gravity.RIGHT|Gravity.CENTER_VERTICAL);
			creditMoney.setText(BDUtil.getWon(mainViewMoney.toString()) + shape);
			viewQuery.setOnClick(leftTitle4, key[3], 3);
			viewQuery.setOnClick(creditMoney, key[3], 3);
		}
		else
		{
			creditMoney.setGravity(Gravity.CENTER);
			creditMoney.setText("비밀");
			viewQuery.setOnClick(leftTitle4, key[3], 3);
			viewQuery.setOnClick(creditMoney, key[3], 3);
		}
		
		middleTitle1.setText(viewQuery.getName(key[4], 4, 1));
		monthInMoney.setTextColor(viewQuery.getColor(key[4]));
		
		if (!key[4].equals(WidgetGetSqlQuery.SECRET))
		{
			mainViewMoney = viewQuery.getMoney(key[4], 4, 1);
			monthInMoney.setText(BDUtil.getWon(mainViewMoney.toString()) + shape);
			viewQuery.setOnClick(middleTitle1, key[4], 4);
			viewQuery.setOnClick(monthInMoney, key[4], 4);
		}
		else
		{
			monthInMoney.setText("비밀");
			viewQuery.setOnClick(middleTitle1, key[4], 4);
			viewQuery.setOnClick(monthInMoney, key[4], 4);
		}
		
		middleTitle2.setText(viewQuery.getName(key[5], 5, 1));
		monthOutMoney.setTextColor(viewQuery.getColor(key[5]));
		
		if (!key[5].equals(WidgetGetSqlQuery.SECRET))
		{
			mainViewMoney = viewQuery.getMoney(key[5], 5, 1);
			monthOutMoney.setText(BDUtil.getWon(mainViewMoney.toString()) + shape);
			viewQuery.setOnClick(middleTitle2, key[5], 5);
			viewQuery.setOnClick(monthOutMoney, key[5], 5);
		}
		else
		{
			monthOutMoney.setText("비밀");
			viewQuery.setOnClick(middleTitle2, key[5], 5);
			viewQuery.setOnClick(monthOutMoney, key[5], 5);
		}
		
		middleTitle3.setText(viewQuery.getName(key[6], 6, 1));
		monthPostMoney.setTextColor(viewQuery.getColor(key[6]));
		
		if (!key[6].equals(WidgetGetSqlQuery.SECRET))
		{
			mainViewMoney = viewQuery.getMoney(key[6], 6, 6);
			monthPostMoney.setText(BDUtil.getWon(mainViewMoney.toString()) + shape);
			viewQuery.setOnClick(middleTitle3, key[6], 6);
			viewQuery.setOnClick(monthPostMoney, key[6], 6);
		}
		else
		{
			monthPostMoney.setText("비밀");
			viewQuery.setOnClick(middleTitle3, key[6], 6);
			viewQuery.setOnClick(monthPostMoney, key[6], 6);
		}
		
		middleTitle4.setText(viewQuery.getName(key[7], 7, 1));
		todayInMoney.setTextColor(viewQuery.getColor(key[7]));
		
		if (!key[7].equals(WidgetGetSqlQuery.SECRET))
		{
			mainViewMoney = viewQuery.getMoney(key[7], 7, 1);
			todayInMoney.setText(BDUtil.getWon(mainViewMoney.toString()) + shape);
			viewQuery.setOnClick(middleTitle4, key[7], 7);
			viewQuery.setOnClick(todayInMoney, key[7], 7);
		}
		else
		{
			todayInMoney.setText("비밀");
			viewQuery.setOnClick(middleTitle4, key[7], 7);
			viewQuery.setOnClick(todayInMoney, key[7], 7);
		}
		
		middleTitle5.setText(viewQuery.getName(key[8], 8, 1));
		todayOutMoney.setTextColor(viewQuery.getColor(key[8]));
		
		if (!key[8].equals(WidgetGetSqlQuery.SECRET))
		{
			mainViewMoney = viewQuery.getMoney(key[8], 8, 1);
			todayOutMoney.setText(BDUtil.getWon(mainViewMoney.toString()) + shape);
			viewQuery.setOnClick(middleTitle5, key[8], 8);
			viewQuery.setOnClick(todayOutMoney, key[8], 8);
		}
		else
		{
			todayOutMoney.setText("비밀");
			viewQuery.setOnClick(middleTitle5, key[8], 8);
			viewQuery.setOnClick(todayOutMoney, key[8], 8);
		}
		
		middleTitle6.setText(viewQuery.getName(key[9], 9, 1));
		todayPostMoney.setTextColor(viewQuery.getColor(key[9]));
		
		if (!key[9].equals(WidgetGetSqlQuery.SECRET))
		{
			mainViewMoney = viewQuery.getMoney(key[9], 9, 1);
			todayPostMoney.setText(BDUtil.getWon(mainViewMoney.toString()) + shape);
			viewQuery.setOnClick(middleTitle6, key[9], 9);
			viewQuery.setOnClick(todayPostMoney, key[9], 9);
		}
		else
		{
			todayPostMoney.setText("비밀");
			viewQuery.setOnClick(middleTitle6, key[9], 9);
			viewQuery.setOnClick(todayPostMoney, key[9], 9);
		}
		
//		String sql = "";
//		
//    	String sql = "SELECT id, money FROM bankbook;";
//    	
//    	dbSql.selectMapTile(this, sql, new ParseSelectData()
//		{
//			@Override
//			public void resultData(Cursor c)
//			{
//				int count = c.getCount();
//				
//				int idIndex = c.getColumnIndex("id");
//				int columIndex = c.getColumnIndex("money");
//				c.moveToFirst();
////				int money = 0;
//				BigDecimal money = BigDecimal.ZERO;
//				for (int i = 0; i < count; i++)
//				{
////					money = money + Integer.parseInt(c.getString(columIndex));
//					
//					if (getAddBankBookFlag(c.getInt(idIndex)))
//					{
//						money = money.add(new BigDecimal(c.getString(columIndex)));
//					}
//					
//					c.moveToNext();
//				}
//				
//				if (flagBankMoney)
//				{
//					bankMoney.setGravity(Gravity.RIGHT|Gravity.CENTER_VERTICAL);
//					bankMoney.setText(BDUtil.getWon(money.toString()) + shape);
//				}
//				else
//				{
//					bankMoney.setGravity(Gravity.CENTER);
//					bankMoney.setText("비밀");
//				}
//				dbTotalMoney = dbTotalMoney.add(money);
//			}
//		});
//    	
//    	sql = "SELECT money FROM real_money;";
//    	
//    	dbSql.selectMapTile(this, sql, new ParseSelectData()
//		{
//			@Override
//			public void resultData(Cursor c)
//			{
//				int count = c.getCount();
//				
//				int columIndex = c.getColumnIndex("money");
//				c.moveToFirst();
////				int money = 0;
//				BigDecimal money = BigDecimal.ZERO;
//				for (int i = 0; i < count; i++)
//				{
////					money = money + Integer.parseInt(c.getString(columIndex));
//					money = money.add(new BigDecimal(c.getString(columIndex)));
//					c.moveToNext();
//				}
//				
//				if (flagRealMoney)
//				{
//					realMoney.setGravity(Gravity.RIGHT|Gravity.CENTER_VERTICAL);
//					realMoney.setText(BDUtil.getWon(money.toString()) + shape);
//				}
//				else
//				{
//					realMoney.setGravity(Gravity.CENTER);
//					realMoney.setText("비밀");
//				}
//				
//				dbTotalMoney = dbTotalMoney.add(money);
//			}
//		});
//    	
//    	if (flagTotalMoney)
//    	{
//    		totalMoney.setGravity(Gravity.RIGHT|Gravity.CENTER_VERTICAL);
//    		totalMoney.setText(BDUtil.getWon(dbTotalMoney.toString()) + shape);
//    	}
//    	else
//    	{
//    		totalMoney.setGravity(Gravity.CENTER);
//    		totalMoney.setText("비밀");
//    	}
//		
//		sql = "SELECT outmoney FROM credit_card;";
//    	
//    	dbSql.selectMapTile(this, sql, new ParseSelectData()
//		{
//			@Override
//			public void resultData(Cursor c)
//			{
//				int count = c.getCount();
//				
//				int columIndex = c.getColumnIndex("outmoney");
//				c.moveToFirst();
////				int money = 0;
//				BigDecimal money = BigDecimal.ZERO;
//				for (int i = 0; i < count; i++)
//				{
////					money = money + Integer.parseInt(c.getString(columIndex));
//					money = money.add(new BigDecimal(c.getString(columIndex)));
//					c.moveToNext();
//				}
//				
//				if (flagPostMoney)
//				{
//					creditMoney.setGravity(Gravity.RIGHT|Gravity.CENTER_VERTICAL);
//					creditMoney.setText(BDUtil.getWon(money.toString()) + shape);
//				}
//				else
//				{
//					creditMoney.setGravity(Gravity.CENTER);
//					creditMoney.setText("비밀");
//				}
//			}
//		});
    	
//    	String fanSql = "";
//    	
//    	// 부채 포함여부에 따른 쿼리
//    	if (fanOkNoFlag != 0)
//		{
//			fanSql = BDConstents.FAN_TYPE + ", ";
//		}
//    	
//    	sql = "SELECT outmoney FROM in_out WHERE outmoney not in ('0') and date = "
//    			+ BDUtil.getDateDB(toYear, toMonth+1, toDay) + " and type not in (" 
//    			+ BDConstents.INOUT_TYPE + ", " 
//    			+ BDConstents.OUTIN_TYPE + ", " + fanSql
//    			+ BDConstents.MYBANK_INOUT_TYPE + ")"
//    			+ "UNION ALL "
//			    + "SELECT outmoney FROM in_out WHERE date = " + BDUtil.getDateDB(toYear, toMonth+1, toDay) 
//			    + " and category in ('" 
//			    + BDConstents.CATEGORY_SUSUMONEY + "')";
//    	
//    	dbSql.selectMapTile(this, sql, new ParseSelectData()
//		{
//			@Override
//			public void resultData(Cursor c)
//			{
//				int count = c.getCount();
//				
//				int columIndex = c.getColumnIndex("outmoney");
//				c.moveToFirst();
////				int money = 0;
//				BigDecimal money = BigDecimal.ZERO;
//				for (int i = 0; i < count; i++)
//				{
////					money = money + Integer.parseInt(c.getString(columIndex));
//					money = money.add(new BigDecimal(c.getString(columIndex)));
//					c.moveToNext();
//				}
//				
//				todayOutMoney.setText(BDUtil.getWon(money.toString()) + shape);
//			}
//		});
//    	
//    	fanSql = "";
//    	
//    	// 부채 포함여부에 따른 쿼리
//    	if (fanOkNoFlag != 0)
//		{
//			fanSql = BDConstents.FAN_TYPE + ", ";
//		}
//    	
//    	sql = "SELECT inmoney FROM in_out WHERE inmoney not in ('0') and date = "
//    			+ BDUtil.getDateDB(toYear, toMonth+1, toDay) + " and type not in (" 
//    			+ BDConstents.INOUT_TYPE + ", " 
//    			+ BDConstents.OUTIN_TYPE + ", " + fanSql
//    			+ BDConstents.MYBANK_INOUT_TYPE +")"
//    			+ "UNION ALL "
//			    + "SELECT inmoney FROM in_out WHERE date = " + BDUtil.getDateDB(toYear, toMonth+1, toDay) 
//			    + " and category in ('" 
//			    + BDConstents.CATEGORY_SUSUMONEY + "')";
//    	
//    	dbSql.selectMapTile(this, sql, new ParseSelectData()
//		{
//			@Override
//			public void resultData(Cursor c)
//			{
//				int count = c.getCount();
//				
//				int columIndex = c.getColumnIndex("inmoney");
//				c.moveToFirst();
////				int money = 0;
//				BigDecimal money = BigDecimal.ZERO;
//				for (int i = 0; i < count; i++)
//				{
////					money = money + Integer.parseInt(c.getString(columIndex));
//					money = money.add(new BigDecimal(c.getString(columIndex)));
//					c.moveToNext();
//				}
//				
//				todayInMoney.setText(BDUtil.getWon(money.toString()) + shape);
//			}
//		});
//    	
//    	fanSql = "";
//    	
//    	// 부채 포함여부에 따른 쿼리
//    	if (fanOkNoFlag != 0)
//		{
//			fanSql =  " and type not in ( " + BDConstents.FAN_TYPE + " )";
//		}
//    	
//    	sql = "SELECT postmoney FROM in_out WHERE postmoney not in ('0')" + fanSql + " and date = "
//    			+ BDUtil.getDateDB(toYear, toMonth+1, toDay) + ";";
//    	
//    	dbSql.selectMapTile(this, sql, new ParseSelectData()
//		{
//			@Override
//			public void resultData(Cursor c)
//			{
//				int count = c.getCount();
//				
//				int columIndex = c.getColumnIndex("postmoney");
//				c.moveToFirst();
////				int money = 0;
//				BigDecimal money = BigDecimal.ZERO;
//				for (int i = 0; i < count; i++)
//				{
////					money = money + Integer.parseInt(c.getString(columIndex));
//					money = money.add(new BigDecimal(c.getString(columIndex)));
//					c.moveToNext();
//				}
//				
//				todayPostMoney.setText(BDUtil.getWon(money.toString()) + shape);
//			}
//		});
//    	
//    	// 달 시작일 가져온다
//    	//SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
//    	int startDate = Integer.parseInt(pref.getString(BDConstents.START_DATE, "1"));
//    	
//    	startTextView.setText(startDate + "");
//    	
//    	String firstDate = "";
//    	String lastDate = "";
//    	
//    	// 시작일이 1일이면 원래대로
//    	if (startDate == 1) 
//    	{
//    		firstDate = BDUtil.getDateDB(toYear, toMonth+1, 1);
//    		lastDate = BDUtil.getDateDB(toYear, toMonth+1, 31); 
//    	}
//    	else
//    	{
//    		if (toMonth+1 == 1)
//    		{
//    			// 1월이면 
//    			if (toDay < startDate)
//    			{
//    				// 저번달에 낑겨있으면
//    				// 1월이면 작년 12월 시작일부터 올해 이번달 시작일전날까지
//        			// 이달의 지출
//    				firstDate = BDUtil.getDateDB(toYear-1, 12, startDate);
//    				lastDate = BDUtil.getDateDB(toYear, 1, startDate-1);
//    			}
//    			else
//    			{
//    				// 새달이 시작됐으면
//    				// 1월이면 1월 시작일부터 2월 시작일전날까지
//        			// 이달의 지출
//    				firstDate = BDUtil.getDateDB(toYear, 1, startDate);
//    				lastDate = BDUtil.getDateDB(toYear, 2, startDate-1);
//    			}    			
//    		}
//    		else if (toMonth+1 == 12)
//    		{
//    			// 12월이면 
//    			if (toDay < startDate)
//    			{
//    				// 저번달에 낑겨있으면
//    				// 올해 11월 시작일부터 올해 12월 시작일전날까지
//        			// 이달의 지출
//    				firstDate = BDUtil.getDateDB(toYear, 11, startDate);
//    				lastDate = BDUtil.getDateDB(toYear, 12, startDate-1);
//    			}
//    			else
//    			{
//    				// 새달이 시작됐으면
//    				// 작년 12월 시작일부터 1월 시작일전날까지
//        			// 이달의 지출
//    				firstDate = BDUtil.getDateDB(toYear, 12, startDate);
//    				lastDate = BDUtil.getDateDB(toYear+1, 1, startDate-1);
//    			}
//    		}
//    		else
//    		{
//    			// 1월이 아니면
//    			if (toDay < startDate)
//    			{
//    				// 전달에 낑겨있으면
//    				// 이달의 지출
//    				firstDate = BDUtil.getDateDB(toYear, toMonth, startDate);
//    				lastDate = BDUtil.getDateDB(toYear, toMonth+1, startDate-1);
//    			}
//    			else
//    			{
//    				// 새달이 시작됐으면
//    				// 이달의 지출
//    				firstDate = BDUtil.getDateDB(toYear, toMonth+1, startDate);
//    				lastDate = BDUtil.getDateDB(toYear, toMonth+2, startDate-1);
//    			}
//    		}
//    	}
//    	
//    	fanSql = "";
//    	
//    	// 부채 포함여부에 따른 쿼리
//    	if (fanOkNoFlag != 0)
//		{
//			fanSql = BDConstents.FAN_TYPE + ", ";
//		}
//    	
//    	sql = "SELECT outmoney FROM in_out WHERE date >= " + firstDate + " and date <= " +
//     		   lastDate + " and type not in (" 
//     		   + BDConstents.INOUT_TYPE + ", "
//			   + BDConstents.OUTIN_TYPE + ", " + fanSql
//			   + BDConstents.MYBANK_INOUT_TYPE + ")"
//			   + "UNION ALL "
// 			   + "SELECT outmoney FROM in_out WHERE date >= " + firstDate
// 			   + " and date <= " + lastDate
// 			   + " and category in ('" 
// 			   + BDConstents.CATEGORY_SUSUMONEY + "')";;
// 			   
//    	
//    	dbSql.selectMapTile(this, sql, new ParseSelectData()
//		{
//			@Override
//			public void resultData(Cursor c)
//			{
//				int count = c.getCount();
//				
//				int columIndex = c.getColumnIndex("outmoney");
//				c.moveToFirst();
////				int money = 0;
//				BigDecimal money = BigDecimal.ZERO;
//				for (int i = 0; i < count; i++)
//				{
////					money = money + Integer.parseInt(c.getString(columIndex));
//					money = money.add(new BigDecimal(c.getString(columIndex)));
//					c.moveToNext();
//				}
//				
//				monthOutMoney.setText(BDUtil.getWon(money.toString()) + shape);
//			}
//		});
//    	
//    	fanSql = "";
//    	
//    	// 부채 포함여부에 따른 쿼리
//    	if (fanOkNoFlag != 0)
//		{
//			fanSql = BDConstents.FAN_TYPE + ", ";
//		}
//	
//    	sql = "SELECT inmoney FROM in_out WHERE date >= " + firstDate + " and date <= " +
//				lastDate + " and type not in (" 
//	   			+ BDConstents.INOUT_TYPE + ", " 
//	   			+ BDConstents.OUTIN_TYPE + ", " + fanSql
//	   			+ BDConstents.MYBANK_INOUT_TYPE + ");";
////	   			+ "UNION ALL "
////	   			+ "SELECT inmoney FROM in_out WHERE date >= " + firstDate
////	   			+ " and date <= " + lastDate
////	   			+ " and category in ('" 
////	   			+ BDConstents.CATEGORY_SUSUMONEY + "')";
//    	
//		dbSql.selectMapTile(this, sql, new ParseSelectData()
//		{
//			@Override
//			public void resultData(Cursor c)
//			{
//				int count = c.getCount();
//				
//				int columIndex = c.getColumnIndex("inmoney");
//				c.moveToFirst();
////				int money = 0;
//				BigDecimal money = BigDecimal.ZERO;
//				for (int i = 0; i < count; i++)
//				{
////					money = money + Integer.parseInt(c.getString(columIndex));
//					money = money.add(new BigDecimal(c.getString(columIndex)));
//					c.moveToNext();
//				}
//				
//				monthInMoney.setText(BDUtil.getWon(money.toString()) + shape);
//			}
//		});
//		
//		fanSql = "";
//    	
//    	// 부채 포함여부에 따른 쿼리
//    	if (fanOkNoFlag != 0)
//		{
//    		fanSql =  " and type not in ( " + BDConstents.FAN_TYPE + " )";
//		}
//		
//		if (postCheck == 0)
//		{
//			sql = "SELECT postmoney FROM in_out WHERE date >= " 
//					+ firstDate + " and date <= " 
//					+ lastDate + fanSql + ";";
//			
//			dbSql.selectMapTile(this, sql, new ParseSelectData()
//			{
//				@Override
//				public void resultData(Cursor c)
//				{
//					int count = c.getCount();
//					
//					int columIndex = c.getColumnIndex("postmoney");
//					c.moveToFirst();
////					int money = 0;
//					BigDecimal money = BigDecimal.ZERO;
//					for (int i = 0; i < count; i++)
//					{
////						money = money + Integer.parseInt(c.getString(columIndex));
//						money = money.add(new BigDecimal(c.getString(columIndex)));
//						c.moveToNext();
//					}
//					
//					monthPostMoney.setText(BDUtil.getWon(money.toString()) + shape);
//				}
//			});
//		}
//		else
//		{
//			setPostMoneyTerm();
//		}
	}
	
	private BigDecimal postTermMoney = BigDecimal.ZERO;
	/**
	 * 카드 사용 일자로 카드 사용 금액을 가져온다.
	 */
	private void setPostMoneyTerm()
	{
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		
		int fanOkNoFlag = pref.getInt(BDConstents.FAN_SETTING_OK_NO, 0);
		
		creditResultList = new ArrayList<CreditCardResultDateData>();
		
		dbSql.selectMapTile(this, "SELECT * FROM credit_card_result_date;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int autoynIdx = c.getColumnIndex("autoyn");
				int startdateIdx = c.getColumnIndex("startdate");
				int enddateIdx = c.getColumnIndex("enddate");
				int resultdateIdx = c.getColumnIndex("resultdate");
				int resultflagIdx = c.getColumnIndex("resultflag");
				int linkidIdx = c.getColumnIndex("linkid");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					CreditCardResultDateData creditResultData = new CreditCardResultDateData();
					
					creditResultData.setId(c.getInt(idIdx) + "");
					creditResultData.setName(c.getString(nameIdx));
					creditResultData.setAutoyn(c.getInt(autoynIdx) + "");
					creditResultData.setStartdate(c.getInt(startdateIdx) + "");
					creditResultData.setEnddate(c.getInt(enddateIdx) + "");
					creditResultData.setResultdate(c.getInt(resultdateIdx) + "");
					creditResultData.setResultflag(c.getInt(resultflagIdx) + "");
					creditResultData.setLinkid(c.getInt(linkidIdx) + "");
					
					creditResultList.add(creditResultData);
					
					c.moveToNext();
				}
			}
		});
		
		postTermMoney = BigDecimal.ZERO;
		
		for (int i = 0; i < creditResultList.size(); i++)
		{
			CreditCardResultDateData data = creditResultList.get(i);
			
			String moneykind = data.getName();
			
			int startDay = Integer.parseInt(data.getStartdate());
			int endDay = Integer.parseInt(data.getEnddate());
			
			String firstDate = "";
			String lastDate = "";
			
			if (toDay >= startDay)
			{
				if (startDay == 1)
				{
					firstDate = BDUtil.getDateDB(toYear, toMonth+1, startDay);
					lastDate = BDUtil.getDateDB(toYear, toMonth+1, endDay);
				}
				else if (toMonth == 11)
				{
					firstDate = BDUtil.getDateDB(toYear, toMonth+1, startDay);
					lastDate = BDUtil.getDateDB(toYear+1, 1, endDay);
				}
				else
				{
					firstDate = BDUtil.getDateDB(toYear, toMonth+1, startDay);
					lastDate = BDUtil.getDateDB(toYear, toMonth+2, endDay);
				}
			}
			else
			{
				if (startDay == 1)
				{
					firstDate = BDUtil.getDateDB(toYear, toMonth, endDay);
					lastDate = BDUtil.getDateDB(toYear, toMonth, endDay);
				}
				else if (toMonth == 0)
				{
					firstDate = BDUtil.getDateDB(toYear-1, 12, startDay);
					lastDate = BDUtil.getDateDB(toYear, toMonth+1, endDay);
				}
				else
				{
					firstDate = BDUtil.getDateDB(toYear, toMonth, startDay);
					lastDate = BDUtil.getDateDB(toYear, toMonth+1, endDay);
				}
			}
			
			if (firstDate.equals(""))
			{
				continue;
			}
			
			String fanSql = "";
	    	
	    	// 부채 포함여부에 따른 쿼리
	    	if (fanOkNoFlag != 0)
			{
	    		fanSql =  " and type not in ( " + BDConstents.FAN_TYPE + " )";
			}
			
			String sql = "SELECT postmoney FROM in_out WHERE date >= " 
					+ firstDate + " and date <= " 
					+ lastDate + " and moneykind = '" 
					+ BDUtil.getApostrophe(moneykind) + "'" + fanSql + ";";
			
			dbSql.selectMapTile(this, sql, new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					int count = c.getCount();
					
					int columIndex = c.getColumnIndex("postmoney");
					c.moveToFirst();
//					int money = 0;
					
					for (int i = 0; i < count; i++)
					{
//						money = money + Integer.parseInt(c.getString(columIndex));
						postTermMoney = postTermMoney.add(new BigDecimal(c.getString(columIndex)));
						c.moveToNext();
					}
				}
			});
		}
		
		monthPostMoney.setText(BDUtil.getWon(postTermMoney.toString()) + shape);
	}

	private boolean addFlag = true;
	/**
	 * 통장 디테일 테이블에서 자산 포함인지 미포함인지 값을 가져온다.
	 * @param linkid
	 * @return
	 */
	private boolean getAddBankBookFlag(int linkid)
	{
		addFlag = true;
		
		dbSql.selectMapTile(this, "SELECT addflag FROM bankbook_detail " +
				"WHERE linkid = " + linkid + ";", 
				new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int linkidIdx = c.getColumnIndex("addflag");
				
				c.moveToFirst();
				
				int flag = 0;
				
				for (int i = 0; i < c.getCount(); i++)
				{
					flag = c.getInt(linkidIdx);
					c.moveToNext();
				}
				
				if (flag == 0)
				{
					addFlag = true;
				}
				else
				{
					addFlag = false;
				}
			}
		});
		
		return addFlag;
	}
    
    @Override
    protected void onDestroy()
    {
    	super.onDestroy();
		dbSql.closeDatabese();
//		if (adview != null) {
//			adview.BDAdViewDestroy();
//			adview = null;
//		}
    }
    
    @Override
    public void onBackPressed()
    {
//    	AlertDialog.Builder dialog = new AlertDialog.Builder(this);
//    	dialog.setIcon(android.R.drawable.ic_dialog_alert);
//    	dialog.setTitle("어플종료하기");
//    	dialog.setMessage("어플을 종료 하시겠습니까?");
//    	dialog.setPositiveButton("종료", new DialogInterface.OnClickListener()
//		{
//			@Override
//			public void onClick(DialogInterface dialog, int which)
//			{
//				setScrollPoint();
//				
//				setAutoData();
//				
//				dbSql.closeDatabese();
//				dialog.dismiss();
//				finish();
//			}
//		});
//    	dialog.setNegativeButton("취소", null);
//    	
//    	dialog.show();
    	
    	if (!bankFlag)
		{
			BDUtil.showToast(superContext, "뒤로 버튼을 한번더 누르시면 종료됩니다.");
			bankFlag = true;
			
			backHandler.sendEmptyMessageDelayed(0, 2000);
		}
    	else
    	{
    		setScrollPoint();
			
			setAutoData();
			
			dbSql.closeDatabese();
			finish();
    	}
    }
    
    private Handler backHandler = new Handler()
    {
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			
			if (msg.what == 0)
			{
				bankFlag = false;
			}
		}
    };
    
    /**
     * 지금 스크롤 위치를 기억한다.
     */
    private void setScrollPoint()
	{
    	SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
    	SharedPreferences.Editor editor = pref.edit();
    	
    	editor.putInt(BDConstents.TODAY_SCROLL_X, todayScrollView.getScrollX());
    	editor.putInt(BDConstents.TODAY_SCROLL_Y, todayScrollView.getScrollY());
    	
    	editor.putInt(BDConstents.MONTH_SCROLL_X, monthScrollView.getScrollX());
    	editor.putInt(BDConstents.MONTH_SCROLL_Y, monthScrollView.getScrollY());
    	
    	editor.commit();
	}
    
	@Override
	public void onClick(View v) 
	{
		if (btnEnable)
			btnEnable = false;
		else 
			return;
		
		if (v == mBtnInsert) 
		{
			intent = new Intent(getApplicationContext(), InsertTabActivity.class);
			startActivity(intent);
		} 
		else if (v == mBtnSelect) 
		{
			intent = new Intent(getApplicationContext(), SelectDialogActivity.class);
			startActivity(intent);
			
//			intent = new Intent(getApplicationContext(), SelectActivity.class);
//			startActivity(intent);
		} 
		else if (v == mBtnStats) 
		{
			intent = new Intent(getApplicationContext(), StatsDialogActivity.class);
			startActivity(intent);
		} 
		else if (v == mBtnSetting) 
		{
			intent = new Intent(getApplicationContext(), SettingActivity.class);
			startActivity(intent);
		}
		else if (v == mBtnCashDrawing)
		{
			intent = new Intent(getApplicationContext(), CashTabActivity.class);
			startActivity(intent);
		}
		else if (v == mBtnMyManager)
		{
			intent = new Intent(getApplicationContext(), ManagerTabActivity.class);
			startActivity(intent);
		}
		else if (v == mBtnMyFan)
		{
			intent = new Intent(getApplicationContext(), FanTabActivity.class);
			startActivity(intent);
		}
		else if (v == mBtnMyTips)
		{
			intent = new Intent(getApplicationContext(), TipsActivity.class);
			startActivity(intent);
		}
		else if (v == leftDayButton)
		{
			startLeftDateButton();
		}
		else if (v == rightDayButton)
		{
			startRightDateButton();
		}
		else if (v == leftMonthButton)
		{
			startLeftMonthButton();
		}
		else if (v == rightMonthButton)
		{
			startRightMonthButton();
		}
		
		if (!btnEnable)
			btnEnable = true;
	}
	
	private void setDateOrWeekdayOrData()
	{
		date.setText(viewQuery.getYear()+"년 "+(viewQuery.getMonth()+1)+"월");
    	weekDay.setText(viewQuery.getDay()+"");
    	BDUtil.WeekDayClass wdClass = new BDUtil.WeekDayClass();
    	wdClass = BDUtil.getWeekDayChinese(
    			viewQuery.getYear(), viewQuery.getMonth(), viewQuery.getDay());
    	weekDay2.setText(wdClass.getWeekDayStr());
    	weekDay2.setTextColor(wdClass.getWeekDayColor());
    	weekDay.setTextColor(wdClass.getWeekDayColor());
		setDataSetting();
	}

	private void startLeftDateButton()
	{
//		if (toDay == 1)
//		{
//			if (toMonth == 2)
//			{
//				if (toYear % 4 == 0 && toYear % 100 != 0 || toYear % 400 == 0)
//				{
//					toDay = 29;
//					toMonth--;
//				}
//				else
//				{
//					toDay = 28;
//					toMonth--;
//				}
//			}
//			else if (toMonth == 0)
//			{
//				toYear--;
//				toMonth = 11;
//				toDay = 31;
//			}
//			else if (toMonth == 4 || toMonth == 6 
//					|| toMonth == 9 || toMonth == 11)
//			{
//				toMonth--;
//				toDay = 30;
//			}
//			else
//			{
//				toMonth--;
//				toDay = 31;
//			}
//		}
//		else
//		{
//			toDay--;
//		}
		
		viewQuery.setLeftToday();
		
		BDUtil.startLeftDegrees(dateLayout).setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationStart(Animation animation)
			{
			}
			
			@Override
			public void onAnimationRepeat(Animation animation)
			{
			}
			
			@Override
			public void onAnimationEnd(Animation animation)
			{
//				date.setText(BDUtil.getDate(toYear, (toMonth+1), toDay));
//				weekDay.setText(BDUtil.getWeekDay(toYear, toMonth, toDay));
//				setDataSetting();
			}
		});
		
		BDUtil.startLeftDegrees(toDayLayout).setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationStart(Animation animation)
			{
			}
			
			@Override
			public void onAnimationRepeat(Animation animation)
			{
			}
			
			@Override
			public void onAnimationEnd(Animation animation)
			{
//				date.setText(BDUtil.getDate(toYear, (toMonth+1), toDay));
//				weekDay.setText(BDUtil.getWeekDay(toYear, toMonth, toDay));
				
				setDateOrWeekdayOrData();
			}
		});
	}

	private void startRightDateButton()
	{
//		if (toMonth == 1)
//		{
//			if (toYear % 4 == 0 && toYear % 100 != 0 || toYear % 400 == 0)
//			{
//				if (toDay == 29)
//				{
//					toDay = 1;
//					toMonth = 2;
//				}
//				else
//				{
//					toDay++;
//				}
//			}
//			else
//			{
//				if (toDay == 28)
//				{
//					toDay = 1;
//					toMonth = 2;
//				}
//				else
//				{
//					toDay++;
//				}
//			}
//		}
//		else if (toDay == 31)
//		{
//			if (toMonth == 11)
//			{
//				toYear++;
//				toMonth = 0;
//				toDay = 1;
//			}
//			else
//			{
//				toMonth++;
//				toDay = 1;
//			}
//		}
//		else if (toDay == 30) 
//		{
//			if (toMonth == 3 || toMonth == 5 || toMonth == 8
//					|| toMonth == 10)
//			{
//				toMonth++;
//				toDay = 1;
//			}
//			else
//			{
//				toDay++;
//			}
//		}
//		else
//		{
//			toDay++;
//		}
		
		viewQuery.setRightToday();
		
		BDUtil.startRightDegrees(dateLayout).setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationStart(Animation animation)
			{
			}
			
			@Override
			public void onAnimationRepeat(Animation animation)
			{
			}
			
			@Override
			public void onAnimationEnd(Animation animation)
			{
//				date.setText(BDUtil.getDate(toYear, (toMonth+1), toDay));
//				weekDay.setText(BDUtil.getWeekDay(toYear, toMonth, toDay));
//				setDataSetting();
			}
		});
		
		BDUtil.startRightDegrees(toDayLayout).setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationStart(Animation animation)
			{
			}
			
			@Override
			public void onAnimationRepeat(Animation animation)
			{
			}
			
			@Override
			public void onAnimationEnd(Animation animation)
			{
//				date.setText(BDUtil.getDate(toYear, (toMonth+1), toDay));
//				weekDay.setText(BDUtil.getWeekDay(toYear, toMonth, toDay));
				setDateOrWeekdayOrData();
			}
		});
	}
	
	private void startLeftMonthButton()
	{
//		if (toMonth == 0)
//		{
//			toYear--;
//			toMonth = 11;
//		}
//		else
//		{
//			toMonth--;
//		}
//		
//		if (toDay > 30)
//		{
//			if (toMonth == 1)
//			{
//				if (toYear % 4 == 0 && toYear % 100 != 0 || toYear % 400 == 0)
//				{
//					toDay = 29;
//				}
//				else
//				{
//					toDay = 28;
//				}
//			}
//			else
//			{
//				toDay = 30;
//			}
//		}
		
		viewQuery.setLeftMonth();
		
		BDUtil.startLeftDegrees(dateLayout).setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationStart(Animation animation)
			{
			}
			
			@Override
			public void onAnimationRepeat(Animation animation)
			{
			}
			
			@Override
			public void onAnimationEnd(Animation animation)
			{
//				date.setText(BDUtil.getDate(toYear, (toMonth+1), toDay));
//				weekDay.setText(BDUtil.getWeekDay(toYear, toMonth, toDay));
//				setDataSetting();
			}
		});
		
		BDUtil.startLeftDegrees(toMonthLayout).setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationStart(Animation animation)
			{
			}
			
			@Override
			public void onAnimationRepeat(Animation animation)
			{
			}
			
			@Override
			public void onAnimationEnd(Animation animation)
			{
//				date.setText(BDUtil.getDate(toYear, (toMonth+1), toDay));
//				weekDay.setText(BDUtil.getWeekDay(toYear, toMonth, toDay));
				setDateOrWeekdayOrData();
			}
		});
	}
	
	private void startRightMonthButton()
	{
//		if (toMonth == 11)
//		{
//			toYear++;
//			toMonth = 0;
//		}
//		else
//		{
//			toMonth++;
//		}
//		
//		if (toDay > 30)
//		{
//			if (toMonth == 1)
//			{
//				if (toYear % 4 == 0 && toYear % 100 != 0 || toYear % 400 == 0)
//				{
//					toDay = 29;
//				}
//				else
//				{
//					toDay = 28;
//				}
//			}
//			else
//			{
//				toDay = 30;
//			}
//		}
		
		viewQuery.setRightMonth();
		
		BDUtil.startRightDegrees(dateLayout).setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationStart(Animation animation)
			{
			}
			
			@Override
			public void onAnimationRepeat(Animation animation)
			{
			}
			
			@Override
			public void onAnimationEnd(Animation animation)
			{
//				date.setText(BDUtil.getDate(toYear, (toMonth+1), toDay));
//				weekDay.setText(BDUtil.getWeekDay(toYear, toMonth, toDay));
//				setDataSetting();
			}
		});
		
		BDUtil.startRightDegrees(toMonthLayout).setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationStart(Animation animation)
			{
			}
			
			@Override
			public void onAnimationRepeat(Animation animation)
			{
			}
			
			@Override
			public void onAnimationEnd(Animation animation)
			{
//				date.setText(BDUtil.getDate(toYear, (toMonth+1), toDay));
//				weekDay.setText(BDUtil.getWeekDay(toYear, toMonth, toDay));
				setDateOrWeekdayOrData();
			}
		});
	}
	
	/**
	 * 데이터를 자동으로 백업 하는 부분입니다.
	 */
	private void setAutoData()
	{
		try
		{
			SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
			int fileFlag = pref.getInt(BDConstents.DATA_AUTO_OUT_SETTING, 0);
			
			if (fileFlag == 1)
			{
				return;
			}
			
			if (!isDataCheck())
			{
				return;
			}
			
			int fileCount = pref.getInt(BDConstents.DATA_AUTO_OUT_FILE_COUNT, 31);
			
			File directory2 = new File(Environment.getExternalStorageDirectory() + "/AccountBook");
			
			if (!directory2.exists())
			{
				directory2.mkdir();
			}
			
			File directory = new File(Environment.getExternalStorageDirectory() + "/AccountBook/Auto");
			
			if (!directory.exists())
			{
				directory.mkdir();
			}
			
			File [] files = directory.listFiles(new FilenameFilter()
			{
				@Override
				public boolean accept(File dir, String filename)
				{
					return filename.endsWith(".db");
				}
			});
			
			if (files != null)
			{
				int location = 0;
				long date = Long.MAX_VALUE; 
				
				if (files.length >= fileCount)
				{
					for (int i = 0; i < files.length; i++)
					{
						long tempDate = files[i].lastModified();
						
						if (tempDate < date)
						{
							location = i;
							date = tempDate;
						}
					}
					
					files[location].delete();
				}
			}
			
			setDataBackUp();
			
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * 디비에 데이터가 있는지 확인한다.
	 * @return
	 */
	private boolean isDataCheck()
	{
		int count = 0;
		
		count += getDataCount("in_out");
		count += getDataCount("check_card");
		count += getDataCount("credit_card");
		count += getDataCount("bankbook");
		count += getDataCount("sms");
		count += getDataCount("auto_bank");
		count += getDataCount("auto_mybank");
		count += getDataCount("memo_main");
		count += getDataCount("budget_category");
		count += getDataCount("budget_in_category");
		count += getDataCount("budget_move_category");
		count += getDataCount("macro_list");
		
		if (count == 0)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
	/**
	 * 해당 테이블에 데이터가 있는지 확인한다.
	 * @param tableName
	 * @return
	 */
	private int getDataCount(String tableName)
	{
		DBSQLite.getInstance(this).selectMapTile(superContext, 
				"SELECT * FROM " + tableName, new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				dbCount = c.getCount();
			}
		});
		
		return dbCount;
	}
	
	private int setDataBackUp()
	{
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH);
		int day = cal.get(Calendar.DAY_OF_MONTH);
		
		DBSQLite.getInstance(this).closeDatabese();
		
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try
		{
			File readfile = new File("/data/data/" 
					+ getPackageName() + "/" 
					+ DBSQLite.dataBaseName);
			
			if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
			{
				return 1;
			}
			
			fis = new FileInputStream(readfile);
			
			File directory = new File(Environment.getExternalStorageDirectory() + "/AccountBook/Auto");
			
			if (!directory.exists())
			{
				directory.mkdir();
			}
			
			File writefile = new File(directory + "/" + BDConstents.AUTO_FILE_NAME 
					+ BDUtil.getDateFile(year, month+1, day) + ".db");
			
			fos = new FileOutputStream(writefile);
			
			byte [] buffer = new byte[1024];
			
			int bufBytes = 0;
			while ((bufBytes = fis.read(buffer)) != -1) 
			{
				fos.write(buffer, 0, bufBytes);
			}
			fos.flush();
			
		} catch (Exception e)
		{
			return 2;
		} finally {
			try
			{
				if (fis != null) fis.close();
				if (fos != null) fos.close();
				DBSQLite.getInstance(this);
			} catch (IOException e)
			{
				e.printStackTrace();
				return 2;
			}
		}
		
		return 0;
	}
	
	@Override
	protected void tipButton()
	{
	}
	
}